
<template>
  <el-form ref="form" :model="data" :rules="rules" label-width="100px">
    <el-form-item label="示例文本" prop="demo_text">
      <el-input v-model.trim="data.demo_text" placeholder="请填写示例文本" />
    </el-form-item>
    <el-form-item label="示例文本域">
      <el-input
        type="textarea"
        rows="3"
        v-model.trim="data.demo_textarea"
      ></el-input>
    </el-form-item>
    <el-form-item label="示例数字" prop="demo_number">
      <el-input-number
        v-model="data.demo_number"
        :min="1"
        :max="10"
        label="示例数字"
      ></el-input-number>
    </el-form-item>
    <el-form-item label="示例密码" prop="demo_pass">
      <el-input
        v-model.trim="data.demo_pass"
        show-password
        placeholder="请填写示例密码"
      />
    </el-form-item>
    <el-form-item label="示例单选">
      <el-radio-group v-model="data.demo_radio">
        <el-radio label="1">选项1</el-radio>
        <el-radio label="2">选项2</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="示例多选">
      <el-checkbox-group v-model="data.demo_chekbox">
        <el-checkbox label="1">选项1</el-checkbox>
        <el-checkbox label="2">选项2</el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item label="示例下拉单选" prop="demo_select">
      <el-select
        v-model.trim="data.demo_select"
        placeholder="请选择示例下拉单选"
        clearable
        class="filter-item"
      >
        <el-option label="选项1" value="1"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="示例下拉多选" prop="demo_selects">
      <el-select
        v-model.trim="data.demo_selects"
        multiple
        placeholder="请选择示例下拉多选"
        clearable
        class="filter-item"
      >
        <el-option label="选项1" value="1"></el-option>
        <el-option label="选项2" value="2"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="示例省市区" prop="demo_district">
      <el-cascader
        size="large"
        :options="address_options"
        clearable
        filterable
        placeholder="选择地区"
        style="width: 250px; margin-right: 10px"
        v-model="selectedOptions"
        @change="handleAddressChange"
      >
      </el-cascader>
    </el-form-item>
    <el-form-item label="示例单图" prop="demo_pic">
      <el-upload
        class="avatar-uploader"
        v-loading="data.demo_pic_loading"
        element-loading-text="图片上传中"
        :action="$store.state.settings.file_upload_url"
        :headers ="headerObj"
        :show-file-list="false"
        accept="image/png, image/jpeg, image/gif, image/jpg"
        :on-success="handledemo_picSuccess"
        :before-upload="beforedemo_picUpload">
            <img v-if="data.demo_pic !=''" :src="data.demo_pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </el-form-item>
    <el-form-item label="示例多图" prop="demo_pics">
      <el-upload
        :action="$store.state.settings.file_upload_url"
        :headers="headerObj"
        multiple
        list-type="picture-card"
        :on-preview="handledemo_picsPreview"
        :file-list="data.demo_picsfileList"
        accept="image/png, image/jpeg, image/gif, image/jpg"
        :on-success="handledemo_picsSuccess"
        :on-remove="handledemo_picsRemove"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="通用文件" prop="demo_files">
      <el-upload
        :action="$store.state.settings.file_upload_url"
        :headers="headerObj"
        multiple
        :file-list="data.demo_fileList"
        accept="image/png, image/jpeg, image/gif, image/jpg,.csv,.xls,.xlsx,.doc,.docx,.ppt,.pptx,.pdf,.zip,.rar"
        :on-success="handledemo_filesSuccess"
        :on-remove="handledemo_filesRemove"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="示例视频" prop="demo_video">
      <el-upload
        action="#"
        ref="demo_video"
        :auto-upload="false"
        :file-list="data.demo_videofileList"
        :on-change="videoChangedemo_video"
        class="avatar-uploader"
        :on-remove="handleRemovedemo_video"
      >
        <video
          ref="demo_video"
          v-if="data.demo_video"
          controls
          style="width: 320px; height: 180px"
          :src="data.demo_video"
        ></video>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-progress
        v-show="
          data.demo_videopercentage > 0 && data.demo_videopercentage < 100
        "
        :percentage="data.demo_videopercentage"
        :text-inside="true"
        :stroke-width="18"
      ></el-progress>
    </el-form-item>
    <!-- <el-form-item label="示例富文本" prop="demo_intro">
                         <tinymce
                    id="editorId"
                  ref="editor"
                  v-model="data.demo_intro"
                    @input="handleInput"
                    @onClick="handleClick"
                  />
                    </el-form-item> -->

    <el-form-item label="示例富文本" prop="demo_intro">
      <editor
        v-model="data.demo_intro" v-if="this.item.dialogVisible"
      />
    </el-form-item>
    <el-form-item label="示例日期">
      <el-date-picker
        type="date"
        key="demo_date"
        value-format="yyyy-MM-dd"
        placeholder="请选择日期"
        v-model="data.demo_date"
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="示例时间">
      <el-time-select
        placeholder="请选择时间"
        v-model="data.demo_time"
      ></el-time-select>
    </el-form-item>
    <el-form-item label="示例日期范围">
      <el-date-picker
        type="daterange"
        value-format="yyyy-MM-dd"
        placeholder="请选择日期"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        range-separator="/"
        v-model="data.damo_range"
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="示例开关">
      <el-switch v-model="data.demo_switch"></el-switch>
    </el-form-item>

    <el-dialog :visible.sync="dialogVisible" width="30%" append-to-body>
      <img width="100%" :src="previewUrl" alt="" />
    </el-dialog>
    <el-form-item>
      <el-button
        type="primary"
        :disabled="$store.state.settings.ajaxButton"
        @click="submit"
        >提交</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { create } from "@/api/demo";
import { getToken } from "@/utils/auth";
import videoUpload from "@/utils/videoUpload";
import { get_video_config, upload_file } from "@/api/common";
import  editor  from "@/components/Editor";
import {
  provinceAndCityData,
  regionData,
  provinceAndCityDataPlus,
  regionDataPlus,
  CodeToText,
  TextToCode,
} from "element-china-area-data";

export default {
  name: "demoCreate",
  components: {editor},
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      
      address_options: regionDataPlus,
      selectedOptions: [],
      loading: false,
      dialogVisible: false,
      previewUrl: "",
      headerObj: {
        Authorization: "Bearer " + getToken(),
      },
      rules: {
        demo_text: [
          { required: true, message: "请输入示例文本", trigger: "blur" },
        ],
      },
      data: {
        demo_pic_loading:false,
        import_url: process.env.VUE_APP_BASE_API + "/admin/demo_import",
        demo_text: "",
        demo_textarea: "",
        demo_number: "",
        demo_pass: "",
        demo_radio: "1",
        demo_chekbox: ["1"],
        demo_select: "",
        demo_selects: "",
        demo_pic: [],
        demo_picpreviewurl: "",
        demo_picfileList: [],
        demo_pics: [],
        demo_files: [],
        demo_picspreviewurl: "",
        demo_picsfileList: [],
        demo_fileList: [],
        demo_video: "",
        demo_videofileList: [],
        demo_videopercentage: 0,
        demo_intro: "",
        demo_date: "2022-04-25",
        demo_time: "22-59",
        damo_range: [],
        demo_switch: true,
      },
    };
  },
  mounted() {
  
  },
  created() {},
  methods: {
  
    handleAddressChange(value) {
      let province = CodeToText[value[0]],
        city = CodeToText[value[1]],
        area = CodeToText[value[2]];
      this.data.province = province != "全部" ? province : "";
      this.data.city = city != "全部" ? city : "";
      this.data.area = area != "全部" ? area : "";
    },
    //导出表格
    handleExport() {
      export_excell(
        process.env.VUE_APP_BASE_API + "/admin/demo_exports",
        this.listQuery
      );
    },
    //超过限制上传
    handledemo_picExceed() {
      this.$message.error("只能上传一张图片");
    },
    //单图预览
    handledemo_picPreview(file) {
      this.dialogVisible = true;
      this.previewUrl = file.url;
    },
    //单图移除
    handledemo_picRemove() {
      this.data.demo_pic = "";
    },
    //单图上传成功回调
    handledemo_picSuccess(response, file, fileList) {
      this.$store.commit("settings/SET_AJAX_BUTTON", false);
      this.data.demo_pic_loading = false 
      if (response.data.code == 0) {
        return this.$message.error(response.msg);
      }
      this.data.demo_pic = response.data.src;
    },
    //单图上传前回调
    beforedemo_picUpload(file) {
      this.data.demo_pic_loading = true 
      this.$store.commit("settings/SET_AJAX_BUTTON", true);
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      if (!isJPG && !isPNG) {
       return  this.$message.error("上传头像图片只能是 JPG 、PNG格式!");
      }
      this.$message.success('上传成功');
    },
    //多图预览
    handledemo_picsPreview(file) {
      this.dialogVisible = true;
      this.previewUrl = file.url;
    },
    //多图移除
    handledemo_picsRemove(file, fileList) {
      const that = this;
      let index = this.data.demo_picsfileList.findIndex(
        (item) => item.url == file.url
      ); // 要删除的数组下标
      if (index != -1) {
        that.data.demo_picsfileList.splice(index, 1);
        that.data.demo_pics.splice(index, 1);
      }
    },
    //多图上传成功回调
    handledemo_picsSuccess(response, file, fileList) {
      this.$store.commit("settings/SET_AJAX_BUTTON", false);
      if (!response.data.src) {
        this.data.demo_picsfileList = [];
        return this.$message.error(response.msg);
      }
      this.data.demo_pics.push(response.data.src);
    },
    //多图上传前回调
    beforedemo_picsUpload(file) {
      this.$store.commit("settings/SET_AJAX_BUTTON", true);
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG 、PNG格式!");
      }
    },
    //删除视频
    handleRemovedemo_video() {
      this.data.demo_video = "";
      this.data.demo_videofileList = [];
    },
    // 文件上传删除
    handledemo_filesRemove(file, fileList) {
      const that = this;
      const fileSrc = file.response.data.src;
      this.data.demo_files.forEach(function (element, key) {
        if (element === fileSrc) {
          that.data.demo_files.splice(key, 1);
        }
      });
    },
    //文件上传成功回调
    handledemo_filesSuccess(response, file, fileList) {
      this.$store.commit("settings/SET_AJAX_BUTTON", false);
      this.data.demo_files.push(response.data.src);
    },
    //视频文件上传回调
    videoChangedemo_video(file, fileList) {
      var that = this;
      get_video_config().then((res) => {
        if (res.code && res.code == 1 && res.data.uploadType != "local") {
          videoUpload.upload(res.data.uploadType, {
              token: "",
              file: file,
              accessKeyId: res.data.accessKey,
              accessKeySecret: res.data.secretKey,
              bucketName: res.data.storageName,
              region: res.data.storageRegion,
              domain: res.data.uploadUrl,
              static_path: res.data.static_path,
              static_url: res.data.static_url,
              uploadIng: function (progress) {
                that.$set(that.data, "demo_videopercentage", progress);
              },
            })
            .then(function (res) {
              that.data.demo_video = res.url;
              that.$message.success("上传成功");
            })
            .catch(function (err) {
              that.$message.error(err);
            });
        } else if (res.data.uploadType == "local") {
          //本地上传
          const fd = new FormData();
          fd.append("file", file.raw);
          upload_file(fd, function (progress) {
            if (progress.lengthComputable) {
              //是否存在进度
              var percentCompleted = Math.round(
                (progress.loaded * 100) / progress.total
              );
              that.$set(that.data, "demo_videopercentage", percentCompleted);
            }
          }).then((res) => {
            if (res.code == 1) {
              that.data.demo_video = res.data.src;
            } else {
              that.$message.error(res.msg);
            }
          });
        } else {
          this.$message.error("获取上传配置失败，请检查");
        }
      });
    },

    //提交表单
    submit() {
      const thiz = this;
      //验证
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        create({
          demo_text: this.data.demo_text,
          demo_number: this.data.demo_number,
          demo_pass: this.data.demo_pass,
          demo_radio: this.data.demo_radio,
          demo_chekbox: this.data.demo_chekbox.join(","),
          demo_select: this.data.demo_select,
          demo_selects: this.data.demo_selects.join(","),
          demo_pic: this.data.demo_pic,
          demo_pics: this.data.demo_pics.join(","),
          demo_files: this.data.demo_files.join(","),
          demo_video: this.data.demo_video,
          demo_intro: this.data.demo_intro,
          demo_date: this.data.demo_date,
          demo_time: this.data.demo_time,
          damo_range: this.data.damo_range.join("/"),
          demo_switch: this.data.demo_switch ? 1 : 0,
        }).then((response) => {
          this.$store.commit("settings/SET_AJAX_BUTTON", true);
          this.$message({
            message: "添加成功",
            type: "success",
            duration: 1500,
            onClose() {
              if (thiz.$refs.form !== undefined) {
                thiz.$refs.form.resetFields();
                thiz.data.demo_picfileList = [];
                thiz.data.demo_picsfileList = [];
                thiz.data.demo_videofileList = [];
              }
              thiz.item.dialogVisible = false;
            },
          });
        });
      });
    },
  },
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
